package cn.stylefeng.guns.modular.business.utils;

import static cn.stylefeng.roses.kernel.file.api.constants.FileConstants.DEFAULT_BUCKET_NAME;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.util.List;

import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.stylefeng.guns.modular.business.entity.Rule;


public class WriteFileUtils {
	    /**
	     * 写到资源文件
	     * 
	     * @param students
	     * @throws IOException
	     */
	    public static void writeToResource(List<Rule> rules) throws IOException {
	        String studentResourcePath = new File(ScctcConst.FILE_PATH+File.separator+DEFAULT_BUCKET_NAME , File.separator+ScctcConst.EXPORTR_RULE_NAME).getAbsolutePath();
	        // 保证目录一定存在
	        ensureDirectory(studentResourcePath);
	        System.out.println("studentResourcePath = " + studentResourcePath);
	        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(studentResourcePath)));
	        for (Rule rule : rules) {
	            StringBuffer buffer = new StringBuffer();
	            buffer.append("rule");
	            buffer.append("\t");
	            buffer.append(rule.getRuleCode());
	            buffer.append("\r\n");
	            buffer.append("{");
	            buffer.append("\r\n");
	            buffer.append("\t");
	            buffer.append("meta:");
	            buffer.append("\r\n").append("\t");
	            buffer.append(rule.getRuleMeta());
	            buffer.append("\r\n");
	            buffer.append("\t");
	            buffer.append("strings:");
	            buffer.append("\r\n").append("\t");
	            buffer.append(rule.getRuleStrings());
	            buffer.append("\r\n");
	            buffer.append("\t");
	            buffer.append("condition:");
	            buffer.append("\r\n").append("\t");
	            buffer.append(rule.getRuleCondition());
	            buffer.append("\r\n");
	            buffer.append("}");
	            buffer.append("\r\n").append("\r\n");
	            writer.write(buffer.toString());
	        }
	        writer.flush();
	        writer.close();
	    }
	    /**
	     * 保证拷贝的文件的目录一定要存在
	     * 
	     * @param filePath
	     *            文件路径
	     */
	    public static void ensureDirectory(String filePath) {
	        if (StringUtils.isEmpty(filePath)) {
	            return;
	        }
	        filePath = replaceSeparator(filePath);
	        if (filePath.indexOf("/") != -1) {
	            filePath = filePath.substring(0, filePath.lastIndexOf("/"));
	            File file = new File(filePath);
	            if (!file.exists()) {
	                file.mkdirs();
	            }
	        }
	    }
	    /**
	     * 将符号“\\”和“\”替换成“/”,有时候便于统一的处理路径的分隔符,避免同一个路径出现两个或三种不同的分隔符
	     * 
	     * @param str
	     * @return
	     */
	    public static String replaceSeparator(String str) {
	        return str.replace("\\", "/").replace("\\\\", "/");
	    }
	    /**
	     * 获取项目根路径
	     * 
	     * @return
	     */
	    public static String getResourceBasePath() {
	        // 获取跟目录
	        File path = null;
	        try {
	            path = new File(ResourceUtils.getURL("classpath:").getPath());
	        } catch (FileNotFoundException e) {
	            // nothing to do
	        }
	        if (path == null || !path.exists()) {
	            path = new File("");
	        }
	        String pathStr = path.getAbsolutePath();
	        // 如果是在eclipse中运行，则和target同级目录,如果是jar部署到服务器，则默认和jar包同级
	        pathStr = pathStr.replace("\\target\\classes", "");
	        return pathStr;
	    }
	    
	    
        //读取json文件
        public static String readJsonFile(String fileName) {
            String jsonStr = "";
            try {
                File jsonFile = new File(fileName);
                FileReader fileReader = new FileReader(jsonFile);
                Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
                int ch = 0;
                StringBuffer sb = new StringBuffer();
                while ((ch = reader.read()) != -1) {
                    sb.append((char) ch);
                }
                fileReader.close();
                reader.close();
                jsonStr = sb.toString();
                return jsonStr;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }


        public static void main(String[] args) {
//            String path = WriteFileUtils.class.getClassLoader().getResource("nihao.rules").getPath();
            String path =  new File(ScctcConst.FILE_PATH+File.separator+DEFAULT_BUCKET_NAME , File.separator+"nihao.rules").getAbsolutePath();
            String s = readJsonFile(path);
            String[] split = s.split("}\n\n");
			System.out.println(split.length);
            JSONObject json = null;
            for (int i = 0; i < split.length; i++) {
				String info = split[i];
				String[] infoLines = info.split("\n",2);
				json = new JSONObject();
				json.put("rulecode", infoLines[0].split(" ")[1]);
				String[] metasplit = infoLines[1].split("strings:");
				String[] split2 = metasplit[0].split("meta:");
				json.put("rulemeta", split2[split2.length-1]);
				String[] stringsAndcondition = metasplit[1].split("condition:");
				json.put("rulestrings", stringsAndcondition[0]);
				json.put("rulescondition", stringsAndcondition[1]);
				System.out.println(String.valueOf(i)+json);
			}
        }
	    
	}
